package com.ror.java.se.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Demo13Unzip {
    public static void main(String[] args) throws IOException {
        File src = new File("assets/io/zip/a-mac.zip");
        File dest = new File("assets/io/zip/a-unzip");
        unzip(src, dest);
    }

    static void unzip(File src, File dest) throws IOException {
        ZipInputStream zis = new ZipInputStream(new FileInputStream(src));
        ZipEntry ze;
        while ((ze = zis.getNextEntry()) != null) {
            System.out.println(ze.getName()); //log
            //排除macOS压缩时掺的“垃圾”文件
            if (ze.getName().startsWith("__MACOSX")) continue;
            File path = new File(dest, ze.getName());
            if (ze.isDirectory()) path.mkdirs();
            else zipFileOutput(zis, path);
        }
        zis.close();
    }

    static void zipFileOutput(ZipInputStream zis, File file) throws IOException {
        FileOutputStream fos = new FileOutputStream(file);
        byte[] buf = new byte[1024];
        int len;
        while ((len = zis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fos.close();
        //关闭当前ZipEntry对象以转到下一个
        zis.closeEntry();
    }
}
